package com.elitel.frame.base.service.strategy.sql;

import com.elitel.frame.main.entity.BaseQueryfield;
import com.elitel.frame.main.entity.enums.ParseSQLEnum;
import com.elitel.frame.main.entity.ext.DBServer;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SQL解析策略类
 *
 * @author xqh
 * @since 2024-9-13 16:53:10
 */
@Component
public class FreemarkerParseSQLStrategy extends ParseSQLStrategy {

    /**
     * 获取策略
     *
     * @return 策略枚举
     */
    protected ParseSQLEnum getTypeEnum() {
        return ParseSQLEnum.freemarker;
    }


    public List<BaseQueryfield> parseSQLQueryField(DBServer server) {
        Pattern compile = Pattern.compile("\\$\\{(.*?)\\}");
        Matcher matcher = compile.matcher(server.getSql());
        List<BaseQueryfield> baseQueryFields = new ArrayList<>();

        HashSet<String> codeSet = new HashSet<>();
        while (matcher.find()) {
            String variableName = matcher.group(1);
            // 防止重复添加参数
            if (codeSet.contains(variableName)) continue;
            codeSet.add(variableName);
            BaseQueryfield baseQueryfield = new BaseQueryfield();
            baseQueryfield.setGuid(UUID.randomUUID().toString());
            baseQueryfield.setServiceid(server.getGuid());
            baseQueryfield.setServicetype(4);
            baseQueryfield.setShowtype(0);
            baseQueryfield.setParametercode(variableName);
            baseQueryfield.setParametervalue(variableName);
            baseQueryFields.add(baseQueryfield);
        }

        return baseQueryFields;
    }

}
